import src from './source';
import * as _ from './common';
import { toJS } from 'mobx';
import * as InputUtil from './inputUtil';
// import ___Calculate from './caculate_wev8'
//获取字段ID
const getFieldid = (fieldMark) =>{
    if(fieldMark.indexOf("_") > -1)
        fieldMark = fieldMark.substring(0, fieldMark.indexOf("_"));
    if(fieldMark.indexOf("field") > -1)
        fieldMark = fieldMark.substring(5);
    return fieldMark;
}

//获取字段基础信息
export const getFieldAttr = (fieldMark) =>{
    const fieldid = getFieldid(fieldMark);
    let fieldAttr = null;
    const { fieldAttrMap } = src.layoutStore;
    if(fieldAttrMap.has(fieldid))
        fieldAttr = fieldAttrMap.get(fieldid);
    return fieldAttr;
}

//获取字段值
export const getFieldValue = (fieldid, rowIndex, convertNum) =>{
    const fieldObj = getFieldValObj(fieldid, rowIndex);
    return convertNum === true ? fieldObj.numValue : fieldObj.value;
}

//获取字段值对象
export const getFieldValObj = (fieldid, rowIndex) =>{
    const { fieldAttrMap } = src.layoutStore;
    if(!fieldAttrMap.has(fieldid.toString())){
        /* eslint no-console: 0 */
        if(window.console)  console.error(`getFieldValObj ${fieldid} Not Exist`);
        return null;
    }
    const tableMark = fieldAttrMap.get(fieldid.toString()).tableMark;
    const fieldMark = tableMark.indexOf("detail") === -1 ? `field${fieldid}` : `field${fieldid}_${rowIndex}`;
    return getFieldObj(fieldMark, tableMark);
}

//获取字段值对象
export const getFieldObj = (fieldMark, tableMark) =>{
    if(!tableMark)
        return null;
    if(tableMark.indexOf("detail") === -1)
        return getMainFieldObj(fieldMark);
    else
        return getDetailFieldObj(fieldMark, tableMark);
}

//获取主表字段值对象
export const getMainFieldObj = (fieldMark) =>{
    const { mainData } = src.layoutStore;
    let fieldObj = null;
    if(mainData.has(fieldMark))
        fieldObj = mainData.get(fieldMark);
    else
        fieldObj = new src.FieldEntity();
    return fieldObj;
}

//获取明细表字段值对象
export const getDetailFieldObj = (fieldMark, tableMark) =>{
    const { detailMap } = src.layoutStore;
    let fieldObj = null;
    const detailObj = detailMap.get(tableMark);
    const detailData = detailObj.detailData;
    if(detailData.has(fieldMark))
        fieldObj = detailData.get(fieldMark);
    else
        fieldObj = new src.FieldEntity();
    return fieldObj;
}

//根据字段id取对应字段值
export const getRelateFieldValue = (fieldid, rowIndex) =>{
    const fieldidArr = [fieldid];
    const relateFieldValues = getRelateFieldValues(fieldidArr, rowIndex);
    return relateFieldValues[fieldid] || "";
}

//根据字段id集合获取对应字段值
export const getRelateFieldValues = (fieldidArr=[], rowIndex) =>{
    let result = {};
    const { mainData,detailMap,fieldAttrMap } = src.layoutStore;
    fieldidArr.map(fieldid =>{
        let fieldValue = "";
        if(fieldAttrMap.has(fieldid.toString())){
            const tableMark = fieldAttrMap.get(fieldid.toString()).tableMark;
            if(tableMark === "main"){
                fieldValue = mainData.has(`field${fieldid}`) ? mainData.get(`field${fieldid}`).value : "";
            }else if(tableMark.indexOf("detail_") > -1){
                const detailObj = detailMap.get(tableMark);
                const detailData = detailObj.detailData;
                fieldValue = detailData.has(`field${fieldid}_${rowIndex}`) ? detailData.get(`field${fieldid}_${rowIndex}`).value : "";
            }
        }
        result[fieldid] = fieldValue.toString();
    });
    return result;
}

//根据字段id集合获取选择框字段对应显示值
export const getRelateFieldShowName = (fieldidArr=[], rowIndex) =>{
    const { fieldAttrMap } = src.layoutStore;
    let result = {};
    fieldidArr.forEach(field =>{
        const fieldid = field.split("_")[0];
        const info = fieldAttrMap.has(fieldid) ? toJS(fieldAttrMap.get(fieldid)) : {};
        if(info.htmltype === 5){    //选择框
            const fieldMark = info.isDetail ? `field${fieldid}_${rowIndex}` : `field${fieldid}`;
            result[`${fieldMark}_span`] = getSelectShowName(fieldMark, ",");
        }
    });
    return result;
}

//获取选择框字段类型的显示值
export const getSelectShowName = (fieldMark, splitChar) =>{
    if(fieldMark.indexOf("field") === -1)
        return "";
    if(typeof splitChar === "undefined" || splitChar === "")
        splitChar = ",";
    let showname = "";
    const { fieldAttrMap } = src.layoutStore;
    const index = fieldMark.indexOf("_");
    const fieldid = index>-1 ? fieldMark.substring(5, index) : fieldMark.substring(5);
    const rowIndex = index>-1 ? fieldMark.substring(index+1) : -1;
    const fieldValue = getFieldValue(fieldid, rowIndex);
    const info = fieldAttrMap.has(fieldid) ? toJS(fieldAttrMap.get(fieldid)) : {};
    if(fieldValue !== "" && info.htmltype === 5 && info.selectattr){
        const selectitemlist = info.selectattr.selectitemlist || [];
        let valueArray = fieldValue.split(",");
        valueArray = valueArray.filter(v => v !== "");
        selectitemlist.map(item =>{
            if(item.selectvalue !== "" && _.indexOf(valueArray, item.selectvalue+"") > -1){
                if(showname !== "")
                    showname += splitChar;
                showname += item.selectname;
            }
        });
    }
    return showname;
}

//转换系统字段名称 
export const convertSystemFieldName = (fieldname) => {
	switch(fieldname){
		case 'field-1':
			return 'requestname';
		case 'field-2':
			return 'requestlevel';
		case 'field-3':
			return 'messageType';
		case 'field-5':
			return 'chatsType';
		default:
			return fieldname;
	}
}

//修改Store值前，做字段值处理
export const convertValueBeforeChangeStore = (value, fieldAttr) =>{
    if(_.isEmpty(fieldAttr))
        return value;
    const htmltype = fieldAttr.htmltype;
    const detailtype = fieldAttr.detailtype;
    let newValue = value;
    if(htmltype === 1){
        if(detailtype === 1){
            newValue = convertSpecialChar(newValue);
        }else{  //数值字段格式化
            newValue = convertNumberValue(newValue, fieldAttr);
        }
    }else if(htmltype === 2 && detailtype === 1){
        newValue = convertSpecialChar(newValue);
    }else if(htmltype === 3 && detailtype === 2){   //日期字段格式化
        const reg = /^\d{4}-\d{1,2}-\d{1,2}$/;
        if(!!newValue && !reg.test(newValue))
            newValue = "";
    }else if(htmltype === 3 && detailtype === 19){  //时间字段格式化
        const reg = /^\d{1,2}:\d{1,2}(:\d{1,2})?$/;
        if(!!newValue && !reg.test(newValue))
            newValue = "";
        // //兼容客户自行改数据库时间支持秒varchar(8)情况
        // if(fieldAttr.fielddbtype && parseInt(fieldAttr.fielddbtype.match(/\d+/)[0]) <= 5 && newValue.indexOf(":",3) > -1)
        //     newValue = newValue.substring(0, newValue.indexOf(":",3));
    }else if(htmltype === 4){   //check框只允许0/1值入库
        if(!newValue || (newValue.toString() !== "0" && newValue.toString() !== "1"))
            newValue = "0";
    }
    return newValue;
}

//修改Store时，替换特殊字符,转换成提交时需要的格式
export const convertSpecialChar = (str) =>{
    str = str.toString();
    str = str.replace(/<br>|<br( )?\/>/ig, "\n");
    str = str.replace(/&nbsp;/ig, " ");
    str = str.replace(/&lt;/ig, "<");
    str = str.replace(/&gt;/ig, ">");
    str = str.replace(/&quot;/ig, "\"");
    str = str.replace(/&amp;/ig, "&");
    return str;
}

export const restoreSpeicalStr = (str) =>{
    str = str.toString();
    //需先转译
    str = str.replace(/&/ig, "&amp;");
    str = str.replace(/</ig, "&lt;");
    str = str.replace(/>/ig, "&gt;");
    //后转译
    str = str.replace(/\n/ig, "<br>");
    //优化断行，多个空格中首个空格不转译，其余空格转&nbsp;
    //str = str.replace(/ /ig, "&nbsp;");
    //破IE，这样写报错，不支持零宽断言
    //str = str.replace(/(?<= ) /ig,'&nbsp;');
    str = str.replace(/( {2,})/ig, val => " " + val.substring(1).replace(/ /ig,"&nbsp;"));
    str = str.replace(/\"/ig, "&quot;");
    return str;
}

//根据字段信息格式化字段值(浮点数位数、转千分位等)
export const convertNumberValue = (realval, fieldAttr) =>{
	if(realval === null || typeof realval === "undefined")
        return "";
    const isqfw = fieldAttr.detailtype === 5;
    if(isqfw)
        realval = realval.toString().replace(/,/g, "");
    if(!judgeIsNumber(realval))
        return "";
    return convertFloatValue(realval, fieldAttr.qfws, isqfw);
}

//判断值是否属于数字
export const judgeIsNumber = InputUtil.judgeIsNumber;

//浮点数值转换
export const convertFloatValue = InputUtil.convertFloatValue;

//时间字段值补零
export const convertTimeValue = (value) =>{
    const reg = /^\d{1,2}:\d{1,2}(:\d{1,2})?$/;
    if(!!value && reg.test(value)){
        let arr = value.split(":");
        if(arr[0].length === 1)     arr[0] = "0"+arr[0];
        if(arr[1].length === 1)     arr[1] = "0"+arr[1];
        if(arr.length > 2 && arr[2].length === 1)  arr[2] = "0"+arr[2];
        value = arr[0]+":"+arr[1];
        if(arr.length > 2)    value += ":"+arr[2];
    }else
        value = "";
    return value;
}

//计算字段当前时刻的只读/必填属性
export const getFieldCurViewAttr = (fieldMark, fieldObj) =>{
    const fieldAttr = getFieldAttr(fieldMark);
    if(fieldAttr == null)
        return 0;
    const { cellInfo,mainData,detailMap } = src.layoutStore;
    const tableMark = fieldAttr.tableMark;
    if(!fieldObj)
        fieldObj = getFieldObj(fieldMark, tableMark);

    const { variable } = fieldObj;
    const fieldid = getFieldid(fieldMark);
    let viewAttr = parseInt(fieldAttr.viewattr) || 0;     //后台设置的字段属性
    if(viewAttr === 0 && _.has(cellInfo, ["fieldCellInfo", fieldid]))    //字段放在模板上但未设置属性的默认给只读属性
        viewAttr = 1;
    if(fieldAttr.isonlyshow === 1)
        viewAttr = 1;
    if(variable.has("viewAttr")){    //显示属性联动改变的字段属性
        const changeViewAttr = parseInt(variable.get("viewAttr")) || 0;
        if(changeViewAttr === 1 || changeViewAttr === 2 || changeViewAttr === 3)
            viewAttr = changeViewAttr;
    }
    if(viewAttr === 2 || viewAttr === 3){
        const commonParam = src.globalStore.commonParam;
        //已办、提交确认置为只读，提交确认时位置字段需再获取一次，跟随原来的属性
        if(parseInt(commonParam.isviewonly || 0) === 1 || (parseInt(commonParam.isaffirmance || 0) === 1 && fieldObj.fieldType != '9-1'))
            viewAttr = 1;
        //不允许修改已有明细置为只读
        if(tableMark.indexOf("detail_") > -1){
            const detailObj = detailMap.get(tableMark);
            const { attr,detailData,rowInfo } = detailObj;
            const rowIndex = parseInt(fieldMark.substring(fieldMark.indexOf("_")+1));
            if(isNaN(rowIndex))
                return -101;    //明细字段被识别在主布局中
            const rowAttr = rowInfo.get(`row_${rowIndex}`);
            const rowKeyid = rowAttr.get("keyid") || 0;
            if(attr.isedit !== 1 && rowKeyid > 0)
                viewAttr = 1;
        }
    }
    return viewAttr;
}

//渲染组件时，字符还原成可显示DOM格式
export const restoreSpeicalChar = (fieldid, str, htmltype, detailtype, viewAttr) =>{
    if(viewAttr === 1 && ((htmltype === 1 && detailtype ===1) || (htmltype === 2 && detailtype ===1))){     //只读时字符转换成DOM结构
        //部分多行文本框由程序插入html源码，只读情况需显示转译后html内容
        if((htmltype === 1 || htmltype === 2) && detailtype === 1){
            const { isbill } = src.globalStore.commonParam;
            const { propFileCfg } = src.layoutStore;
            const fieldKey = `field${fieldid}_${isbill}`;
            const support_html_textarea_field = propFileCfg.support_html_textarea_field || "";
            if(support_html_textarea_field.indexOf(fieldKey) > -1){
                str = str.replace(/\n/ig, "<br>");
                return str;
            }
        }
        str = restoreSpeicalStr(str);
        //QC966924 统计解决E7升E9单行、多行文本框历史数据乱码问题
        str = str.replace(/&amp;#160;/g, '&nbsp;');
    }
    return str;
}

//计算表达式结果
export const calExpressionResult = (expression) =>{
    const { propFileCfg } = src.layoutStore;
    // const open_server_eval = propFileCfg && propFileCfg.open_server_eval == "1";
    const open_server_eval = false;
    let result = "";
    try{
        if(window.___Calculate && !expression.includes("Math")){
            let calculate =  new window.___Calculate();
            result = calculate.calculateResult(expression);
        }else{
            result = eval(expression)
        }
    }catch(e){
        /* eslint no-console: 0 */
        if(window.console)  console.error("Eval Appear Exception:"+expression);
    }
    return result.toString();
}

//人力资源条件数据处理
export const spellResourceCondition = (datas) =>{
	if(datas){
		let value  = [];
		datas.map((item,index)=>{
            let seclevel = "";
            if(item.seclevel){
                const length = item.seclevel.match(/[-]/g).length
                if(length == 1){
                    seclevel = item.seclevel.replace('-','|@|');
                }else if(length == 2){
                    if(item.seclevel.indexOf("-") == 0){
                        seclevel = item.seclevel.replace(/-/g,'|@|');
                        seclevel = seclevel.replace("|@|",'-');
                    }else{
                        const seclevelArr = item.seclevel.split("-");
                        seclevel = seclevelArr[0]+"|@|"+"-"+seclevelArr[2];
                    }

                }else if(length == 3){
                    const seclevelArr = item.seclevel.split("-");
                    seclevel = "-"+seclevelArr[1]+"|@|"+"-"+seclevelArr[3];
                }
            }
            
			if(item.sharetype  ==  "1"){
        if(item.canDownload){
          value.push(`1_${item.relatedshare}_0_0_${item.canDownload=='是'?1:0}`);
        } else { //移动端人力资源条件字段选完值后，没有回传canDownload属性，处理成默认为是。
          value.push(`1_${item.relatedshare}_0_0_1`);
        }
			}else if(item.sharetype == "2" || item.sharetype == "3"){
        if(item.canDownload){
          value.push(`${item.sharetype}_${item.relatedshare}_0_${seclevel}_${item.canDownload=='是'?1:0}`);
        } else { 
          value.push(`${item.sharetype}_${item.relatedshare}_0_${seclevel}_1`);
        }
			}else if(item.sharetype == "4"){
        if(item.canDownload) {
          value.push(`4_${item.relatedshare}_${item.rolelevel}_${seclevel}_${item.canDownload=='是'?1:0}`);
        } else {
          value.push(`4_${item.relatedshare}_${item.rolelevel}_${seclevel}_1`);
        }
			}else if(item.sharetype == "5"){
        if(item.canDownload) {
          value.push(`5_0_0_${seclevel}_${item.canDownload=='是'?1:0}`);
        } else {
          value.push(`5_0_0_${seclevel}_1`);
        }
			}else if(item.sharetype == "6"){
				if(item.joblevel == '2'){
          if(item.canDownload) {
            value.push(`6_${item.relatedshare}_0_2|@|2_${item.canDownload=='是'?1:0}`);
          } else {
            value.push(`6_${item.relatedshare}_0_2|@|2_1`);
          }
				} else {
          if(item.canDownload) {
            value.push(`6_${item.relatedshare}_0_${item.joblevel}|@|${item.jobfield}_${item.canDownload=='是'?1:0}`)
          } else {
            value.push(`6_${item.relatedshare}_0_${item.joblevel}|@|${item.jobfield}_1`)
          }
				}
			}
		});
		return value.join('~');
	}
	return '';
}

//处理流程多人力操作组信息
export const buildMultiUserGroupInfo = (fieldValueObj={}) =>{
    const ids = fieldValueObj.value;
    const datas = fieldValueObj.specialobj || [];
	const multiUserType = {"subcom":2,"dept":3,"group":4,"virtual_subcom":5,"virtual_dept":7,"all":9};
	let groupInfo = {};
    let i = 0;
    datas && datas.map((v,k)=>{
        const type  =  v.type;
        const typeid  = v.id||0;
        if(type  == "subcom" || type == "dept" || type  == "group"){
            const users = v.users;
            let userIds  = [];
            users && users.map((o)=>{
                userIds.push(o.id);
            });
            groupInfo[`group_${i}`] = multiUserType[type]+"|"+typeid+"|"+userIds.join(",");
            i++;
        }else if(type == "all"){
            groupInfo[`group_${i}`] = multiUserType[type]+"|"+typeid+"|"+ids;
            i++;
        }
    });
    groupInfo.groupnum = i;
	return groupInfo;
}